package com.wyd.note.business.dict;

import com.querydsl.core.Tuple;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.wyd.common.component.InfoException;
import com.wyd.note.business.test.QTestA;
import org.apache.commons.lang3.time.DateUtils;
import org.jooq.DSLContext;
import org.jooq.Record;
import org.jooq.Result;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import java.text.ParseException;
import java.util.List;

@Service
public class DictService {
    private final DictRepository dictRepository;
    private final DSLContext dslContext;
    private final EntityManager entityManager;
//    private final MySQLQueryFactory mySQLQueryFactory;

    public DictService(DictRepository dictRepository, DSLContext dslContext, EntityManager entityManager) {
        this.dictRepository = dictRepository;
        this.dslContext = dslContext;
        this.entityManager = entityManager;
    }

    public Dict create(Dict dict) {
        return dictRepository.save(dict);
    }

    public Dict update(String id, Dict dict) {
        final Dict dict1 = dictRepository.findById(id).orElseThrow(() -> InfoException.i("0", "数据不存在"));

        dict1.setChinese(dict.getChinese());
        dict1.setEnglish(dict.getEnglish());

        return dictRepository.save(dict1);
    }

    public Result<Record> search() {
//        dslContext.select()
        final Result<Record> fetch = dslContext.fetch("select * from dict order by created_at desc limit ?, ?", 0, 10);

        final QDict dict = QDict.dict;

        return fetch;
        // TODO
//        return dslContext.selectFrom("select * from dict ")
//                .where("chinese like ?chinese")
//                .and("english like ?english ")
//                .bind("chinese", "%1%")
//                .bind("english", "%2%")
//                .fetchArray();
    }

    public List<Dict> querydsl() throws ParseException {
        final QDict qDict = QDict.dict;

        final JPAQueryFactory jpaQueryFactory = new JPAQueryFactory(entityManager);

        final List<Dict> list = jpaQueryFactory.selectFrom(qDict)
                .fetch();

        //

        final QTestA qTestA = QTestA.testA;

        final List<Tuple> list1 = jpaQueryFactory.select(qDict, qTestA).from(qDict).join(qTestA)
                .on(qDict.uuid.eq(qTestA.dictId))
                .where(qTestA.createdAt.gt(DateUtils.parseDate("2020-01-01", "yyyy-MM-dd")))
                .fetch();

        return list;
    }
}
